package com.waitingresult.common.base.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.waitingresult.common.base.domain.qo.BaseQo;
import com.waitingresult.common.base.model.Result;
import com.waitingresult.common.base.service.BaseService;
import com.waitingresult.common.converter.BaseConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.groups.Default;
import java.util.Arrays;
import java.util.Objects;

/**
 * All right reserved,Designed By WangShuai
 *
 * @author : WangShuai
 * @version : V1.0
 * @ClassName : BaseController
 * @Description :
 * @date : 2021/11/24 15:22
 */
@SuppressWarnings("ALL")
public class BaseController<Service extends BaseService, Converter extends BaseConverter, Qo extends BaseQo, Vo> {
    @Autowired
    private Service service;
    @Autowired
    private Converter converter;

    @PostMapping("index")
    public Result<Object> index(@RequestBody @Validated({BaseQo.Query.class, Default.class}) Qo qo) throws InstantiationException, IllegalAccessException {
        IPage pageEntity = Objects.isNull(qo) ? new Page() : new Page<>(qo.getCurrent(), qo.getSize());
        pageEntity = service.page(pageEntity, service.getLamdaQueryWrapper(qo));
        pageEntity.setRecords(converter.entityToVo(pageEntity.getRecords()));
        return Result.success("ok", pageEntity);
    }

    @PostMapping("select")
    public Result<Object> select(@RequestBody(required = false) @Validated({BaseQo.Query.class, Default.class}) Qo qo) {
        return Result.success("ok", converter.entityToVo(service.list(service.getLamdaQueryWrapper(qo))));
    }

    @PostMapping("get")
    public Result<Object> get(Long id) {
        return Result.success("ok", service.getById(id));
    }

    @PostMapping("add")
    public Result<Object> add(@RequestBody(required = false) @Validated({BaseQo.Create.class, Default.class}) Qo qo) {
        return Result.success("ok", service.save(converter.qoToEntity(qo)));
    }

    @PostMapping("edit")
    public Result<Object> edit(@RequestBody(required = false) @Validated({BaseQo.Update.class, Default.class}) Qo qo) {
        return Result.success("ok", service.updateById(converter.qoToEntity(qo)));
    }

    @PostMapping("delete")
    public Result<Object> delete(String ids) {
        return Result.success("ok", service.removeByIds(Arrays.asList(ids.split(","))));
    }
}
